package com.ruoyi.machine.controller;

import com.ruoyi.accounts.controller.StatisticsController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.machine.EmpMachine;
import com.ruoyi.common.core.domain.machine.EmpEquipment;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.machine.annotation.EquipmentLog;
import com.ruoyi.machine.domain.vo.EmpMachineVo;
import com.ruoyi.machine.service.IEmpMachineService;
import com.ruoyi.machine.service.IEmpEquipmentService;
import com.ruoyi.machine.service.IQiniuService1;
import com.ruoyi.system.service.ISysRoleService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 机台列表Controller
 *
 * @author 黄字添
 * @date 2023-12-25
 */
@RestController
@RequestMapping("/machine/manage")
public class EmpMachineController extends BaseController {
    @Autowired
    private IEmpMachineService empMachineService;
    @Autowired
    private IEmpEquipmentService empEquipmentService;
    @Autowired
    private IQiniuService1 qiniuService;

    @Autowired
    private Environment env;
    @Autowired
    private ISysRoleService roleService;
    /**
     * 图片上传
     *
     * @return Result
     */
    @PostMapping("/uploadImg")
    public AjaxResult upload(@RequestBody MultipartFile file) {
        return AjaxResult.success(qiniuService.uploadQNImg(file));
    }

    /**
     * 查询机台列表列表
     */
    @PreAuthorize("@ss.hasPermi('machine:manage:list')")
    @GetMapping("/list")
    public TableDataInfo list(EmpMachineVo empMachine) {
    	int type = getRoleSign();
    	if(empMachine.getDeptId() == null) {
    		if(type == 1) 
        		empMachine.setStoreID(null);
        	
        	if(type == 4) 
        		empMachine.setUid(getUserId());
    		
        	if(type == 5) 
    			 empMachine.setDeptId(getDeptId());
    	}
    	
        startPage();
       
        List<EmpMachine> list = empMachineService.selectEmpMachineList(empMachine);
        return getDataTable(list);
    }
    private int getRoleSign() {
		Long superRole = new Long(Integer.parseInt(env.getProperty("jurisdiction.super")));
    	Long systemRole = new Long(Integer.parseInt(env.getProperty("jurisdiction.system")));
    	Long platformRole = new Long(Integer.parseInt(env.getProperty("jurisdiction.platform")));
    	Long agentRole = new Long(Integer.parseInt(env.getProperty("jurisdiction.agent")));
    	Long storeRole = new Long(Integer.parseInt(env.getProperty("jurisdiction.store")));
    	
    	int type = 6;
    	List<Long> list = roleService.selectRoleListByUserId(getUserId());
    	for(int i = 0 ; i < list.size() ; i ++) {
    		Long userRoleId = list.get(i);
    		
    		if(userRoleId.equals(superRole)) {
    			type = 1;
    			break;
    		}else if (userRoleId.equals(systemRole) && type > 2) {
    			type = 2;
			}else if (userRoleId.equals(platformRole) && type > 3) {
				type = 3;
			}else if (userRoleId.equals(agentRole) && type > 4) {
				type = 4;
			}else if (userRoleId.equals(storeRole)) {
				type = 5;
			}
    	}
		
    	if(type == 6)
    		type = 0;
    	
		return type;
	}

    @GetMapping("/appList")
    public List<EmpMachine> appList(EmpMachineVo empMachine) {
    	if(empMachine.getDeptId() == null) {
    		empMachine.setDeptId(getDeptId());
    	}
         List<EmpMachine> list = empMachineService.selectAppMachineList(empMachine);
         
         return list;
    }
    
    
    @GetMapping("/machineInfo/{machineID}")
    public EmpMachine machineInfo(@PathVariable("machineID") Long machineID) {
        EmpMachine res = empMachineService.selectMachineInfo(machineID); 
        return res;
    }

    /**
     * 查询未绑定的机台列表
     */
    @PreAuthorize("@ss.hasPermi('machine:manage:list')")
    @GetMapping("/getNoUseList")
    public TableDataInfo getNoUseList(EmpMachineVo empMachine) {
        startPage();
        empMachine.setDeptId(getDeptId());
        List<EmpMachine> list = empMachineService.selectEmpMachineNoUseList(empMachine);
        return getDataTable(list);
    }
    
    /**
     * 查询所有机台列表
     */
    @PreAuthorize("@ss.hasPermi('machine:manage:list')")
    @GetMapping("/getAllUseList")
    public TableDataInfo getAllUseList(EmpMachineVo empMachine) {
        startPage();
        empMachine.setDeptId(getDeptId());
        List<EmpMachine> list = empMachineService.selectEmpMachineAllUseList(empMachine);
        return getDataTable(list);
    }
    

    /**
     * 获取机台列表详细信息
     */
    @PreAuthorize("@ss.hasPermi('machine:manage:list')")
    @GetMapping(value = "/{MachineID}")
    public AjaxResult getInfo(@PathVariable("MachineID") Long MachineID) {
        return success(empMachineService.selectEmpMachineByMachineID(MachineID));
    }

    /**
     * 新增机台列表
     */
    @PreAuthorize("@ss.hasPermi('machine:manage:add')")
    @Log(title = "机台列表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EmpMachine empMachine) {
        if (empMachineService.selectEmpMachineByMachineID(empMachine.getMachineID()) != null) {
            return AjaxResult.error("该机台ID已存在，添加失败");
        } else {
            empMachine.setCreatedTime(new Date());
            return toAjax(empMachineService.insertEmpMachine(empMachine));
        }
    }

    /**
     * 修改机台列表
     */
    @PreAuthorize("@ss.hasPermi('machine:manage:edit')")
    @Log(title = "机台列表", businessType = BusinessType.UPDATE)
    @Transactional(rollbackFor = Exception.class)
    @PutMapping
    public AjaxResult edit(@RequestBody EmpMachine empMachine) {
        empMachine.setUpdatedTime(new Date());
        empMachine.setUpdatedBy(getUsername());
        return toAjax(empMachineService.updateEmpMachine(empMachine));
    }

    /**
     * 删除机台列表
     */
    @PreAuthorize("@ss.hasPermi('machine:manage:remove')")
    @Log(title = "机台列表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{MachineIDs}")
    public AjaxResult remove(@PathVariable Long[] MachineIDs) {
        return toAjax(empMachineService.deleteEmpMachineByMachineIDs(MachineIDs));
    }

    /**
     * 导入机台列表
     */
    @Log(title = "机台列表", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('machine:manage:import')")
    @EquipmentLog(title = "导入机台列表")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<EmpMachine> util = new ExcelUtil<EmpMachine>(EmpMachine.class);
        List<EmpMachine> machineList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = empMachineService.importData(machineList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<EmpMachine> util = new ExcelUtil<EmpMachine>(EmpMachine.class);
        util.importTemplateExcel(response, "机台列表");
    }

    /**
     * 导出机台列表
     */
    @PreAuthorize("@ss.hasPermi('machine:manage:export')")
    @Log(title = "机台列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, EmpMachineVo empMachine) {
    	empMachine.setDeptId(getDeptId());
        List<EmpMachine> list = empMachineService.selectEmpMachineList(empMachine);
        ExcelUtil<EmpMachine> util = new ExcelUtil<EmpMachine>(EmpMachine.class);
        util.exportExcel(response, list, "机台列表数据");
    }

    /**
     * 查询所有门店，返回给下拉框
     */
    @PreAuthorize("@ss.hasPermi('store:manage:list')")
    @GetMapping("/listStore")
    public AjaxResult listStore() {
        return success(empMachineService.selectEmpStoreList());
    }

    /**
     * 上线
     */
    @PreAuthorize("@ss.hasPermi('machine:manage:edit')")
    @PutMapping("/handleStatusUp")
    public AjaxResult handleStatusUp(@RequestBody Integer machineID) {
        return toAjax(empMachineService.updateStatusUnLock(Long.valueOf(machineID)));
    }

    /**
     * 下线
     */
    @PreAuthorize("@ss.hasPermi('machine:manage:edit')")
    @PutMapping("/handleStatusDown")
    public AjaxResult handleStatusDown(@RequestBody Integer machineID) {
        return toAjax(empMachineService.handleStatusDown(Long.valueOf(machineID)));
    }

    /**
     * 维护
     */
    @PreAuthorize("@ss.hasPermi('machine:manage:edit')")
    @PutMapping("/handleStatusMaintenance")
    public AjaxResult handleStatusMaintenance(@RequestBody Integer machineID) {
        return toAjax(empMachineService.handleStatusMaintenance(Long.valueOf(machineID)));
    }

    /**
     * 添加在线人数,修改围观状态
     */
    @PreAuthorize("@ss.hasPermi('machine:manage:edit')")
    @Transactional(propagation = Propagation.REQUIRED,
            isolation = Isolation.READ_COMMITTED,
            rollbackFor = Exception.class,
            timeout = 100)
    @PutMapping("/addOnlineNumber")
    public AjaxResult addOnlineNumber( Integer machineID) {
        EmpMachine machine = empMachineService.getOneByID(Long.valueOf(machineID));
        if (Objects.equals(machine.getOnlinePeople(), machine.getMaxPeople())) {
            return AjaxResult.error("该房间人数已满");
        }
        empMachineService.addOnlineNumber(Long.valueOf(machineID));
        return AjaxResult.success("当前在线人数", machine.getOnlinePeople() + 1);
    }

    /**
     * 减少在线人数
     */
    @PreAuthorize("@ss.hasPermi('machine:manage:edit')")
    @Transactional(propagation = Propagation.REQUIRED,
            isolation = Isolation.READ_COMMITTED,
            rollbackFor = Exception.class,
            timeout = 100)
    @PutMapping("/reduceOnlineNumber")
    public AjaxResult reduceOnlineNumber( Integer machineID) {
        EmpMachine machine = empMachineService.getOneByID(Long.valueOf(machineID));
        if (machine.getOnlinePeople() == 0) {
            return AjaxResult.error("警告：该房间为空房间");
        }
        empMachineService.reduceOnlineNumber(Long.valueOf(machineID));
        return AjaxResult.success("当前在线人数", machine.getOnlinePeople() - 1);
    }
    /**
     * 机台管理
     * 门店id storeID
     * @return
     * MachineID：机台id
     * MachineName：机台名称
     * CurrencyType：货币类型
     * AdmissionAmount：入场数额
     * CREATED_TIME：创建时间
     * Status：机台状态
     * OnlinePeople：当前在线人数
     * EquipmentModel：设备型号
     * */
    @GetMapping("/getMachineList")
    public AjaxResult getMachineList(Long storeID){
        return empMachineService.getMachineList(storeID);
    }
}
